#!/bin/bash
source userdb.env

ridsetnum=`redis-cli -h ${REDIS_IP} -p ${REDIS_PORT} -n ${REDIS_DB} scard "ridset"`
if [ ${ridsetnum} -gt ${REDIS_RIDSET_LEAST} ]; then
	exit 0
fi
#找到当前最大的mysql rid
maxrid=0
tmpmaxrid=0
for dbname in $DBNAMES; do
        tmpmaxrid=`mysql -h$DBIP -u$DBUSER -p$DBPASS $dbname -e "select max(rid) as maxrid from role_auth;"|grep -v "maxrid"`
        if [ ${maxrid} -lt ${tmpmaxrid} ]; then
                maxrid=${tmpmaxrid}
        fi
done
echo "mysql maxrid: ${maxrid}"
#找到最大的redis ridset中最大的rid
cursor=0
istrue=1
isexist=`redis-cli -h ${REDIS_IP} -p ${REDIS_PORT} -n ${REDIS_DB} exists "ridset"`
if [ ${isexist} -ne 0 ]; then
	while [ ${istrue} -ne 0 ]
	do
		ridsetinfo=`redis-cli -h ${REDIS_IP} -p ${REDIS_PORT} -n ${REDIS_DB} sscan "ridset" ${cursor}`
		let j=0
		for value in $ridsetinfo; do
			if [ ${j} -eq 0 ]; then
				cursor=${value}
				j=$((${j}+1))
			elif [ ${maxrid} -lt ${value} ]; then
                maxrid=${value}
			fi
		done
	done	
fi


if [ ${maxrid} -eq 0 ]; then
	maxrid=1000000
fi

echo "maxrid: ${maxrid}"

let i=1
let k=0
while [ ${i} -le ${REDIS_RIDSETINCR_NUM} ]
do
	rid=$((${maxrid}+${i}))
	k=$((${k}+1))
	redis-cli -h ${REDIS_IP} -p ${REDIS_PORT} -n ${REDIS_DB} sadd "ridset" ${rid}
	i=$((${i}+1))
	if [ ${k} -eq 400 ]; then
		k=0
		sleep 0.1		
	fi
done
